package com.jz.community.moduleshoppingguide.search.utils;

import android.content.Context;

import com.jz.community.basecomm.base.BaseSP;
import com.jz.community.basecomm.utils.Preconditions;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by Tony.Fan on 2018/6/1 17:33
 */
public class SearchHistorySpUtils extends BaseSP {

    private ArrayList<String> searchHotWordArr;

    private static SearchHistorySpUtils spUtils = new SearchHistorySpUtils();

    public static SearchHistorySpUtils getInstance() {
        return spUtils;
    }

    @Override
    public String getModelPreferenceFIleName() {
        return "search_history";
    }

    public void saveSearchHotWord(Context context, String text) {
        // 获取搜索框信息
        String old_text = getString(context, "history");
        // 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
        StringBuilder builder = new StringBuilder(old_text);
        builder.append(text + ",");
        // 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
        if (!old_text.contains(text + ",")) {
            putString(context, "history", builder.toString());
        }
    }

    public ArrayList<String> querySearchHotWord(Context context) {
        // 获取搜索记录文件内容
        String history = getString(context, "history");
        if (!Preconditions.isNullOrEmpty(history)) {
            // 用逗号分割内容返回数组
            String[] history_arr = history.split(",");
            searchHotWordArr = new ArrayList<>();

            for (String tvStr : history_arr) {
                searchHotWordArr.add(tvStr);
            }
            Collections.reverse(searchHotWordArr);
            return searchHotWordArr;
        }
        return null;
    }

    //清除搜索记录
    public void cleanHistory(Context context) {
        clear(context);
        if (!Preconditions.isNullOrEmpty(searchHotWordArr)) {
            searchHotWordArr.clear();
        }
    }

}
